from django.test import TestCase, Client
from .models import VideoRecord
from .serializers import VideoRecordSerializer
from django.utils import timezone
import json

class VideoRecordTestCase(TestCase):
    def setUp(self):
        # 创建测试视频记录
        self.video1 = VideoRecord.objects.create(
            timestamp=timezone.now(),
            storage_path='/videos/video1.mp4',
            device_id=1  # 假设设备ID为1
        )
        self.video2 = VideoRecord.objects.create(
            timestamp=timezone.now(),
            storage_path='/videos/video2.mp4',
            device_id=2  # 假设设备ID为2
        )

        self.client = Client()

    def test_list_video_records(self):
        """测试获取所有视频记录"""
        response = self.client.get('/video-records/')
        self.assertEqual(response.status_code, 200)
        video_records = VideoRecord.objects.all()
        serializer = VideoRecordSerializer(video_records, many=True)
        self.assertEqual(response.json(), serializer.data)

    def test_detail_video_record_success(self):
        """测试获取单个视频记录成功"""
        response = self.client.get(f'/video-records/{self.video1.video_id}/')
        self.assertEqual(response.status_code, 200)
        video_record = VideoRecord.objects.get(video_id=self.video1.video_id)
        serializer = VideoRecordSerializer(video_record)
        self.assertEqual(response.json(), serializer.data)

    def test_detail_video_record_not_found(self):
        """测试获取不存在的视频记录"""
        response = self.client.get('/video-records/999/')
        self.assertEqual(response.status_code, 404)
        self.assertEqual(response.json(), {'error': 'Video Record not found'})

    def test_create_video_record(self):
        """测试创建新的视频记录"""
        data = {
            'timestamp': timezone.now().isoformat(),
            'storage_path': '/videos/video3.mp4',
            'device_id': 3
        }
        response = self.client.post('/video-records/', data, content_type='application/json')
        self.assertEqual(response.status_code, 201)
        self.assertTrue(VideoRecord.objects.filter(storage_path='/videos/video3.mp4').exists())

    def test_update_video_record(self):
        """测试更新视频记录"""
        data = {
            'storage_path': '/videos/video1-updated.mp4'
        }
        response = self.client.put(f'/video-records/{self.video1.video_id}/', json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, 200)
        updated_video_record = VideoRecord.objects.get(video_id=self.video1.video_id)
        self.assertEqual(updated_video_record.storage_path, '/videos/video1-updated.mp4')

    def test_delete_video_record(self):
        """测试删除视频记录"""
        response = self.client.delete(f'/video-records/{self.video1.video_id}/')
        self.assertEqual(response.status_code, 204)
        self.assertFalse(VideoRecord.objects.filter(video_id=self.video1.video_id).exists())